<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="档案区编号" prop="archiveAreaNo">
        <el-tree-select v-model="queryParams.archiveAreaNo" :data="ArchiveArchAreaList"
                        :props="{ value: 'archAreaNo', label: 'label', children: 'children' }" value-key="archAreaNo"
                        placeholder="请选择档案区" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="列编号(柜编号)" prop="colNo">
        <el-input v-model="queryParams.colNo" placeholder="请输入列编号(档案柜编号)" clearable
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否固定列" prop="isFixedCol">
        <el-select v-model="queryParams.isFixedCol" placeholder="请选择是否固定列">
          <el-option v-for="dict in column_fixed" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否允许开柜" prop="isOpen">
        <el-select v-model="queryParams.isOpen" placeholder="请选择是否允许开柜">
          <el-option v-for="dict in open_lock" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['archive:ArchiveCabinet:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['archive:ArchiveCabinet:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['archive:ArchiveCabinet:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['archive:ArchiveCabinet:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ArchiveCabinetList" @selection-change="handleSelectionChange">
      <el-table-column label="档案区编号" align="center" prop="archiveAreaNo"/>
      <el-table-column label="列编号(柜编号)" align="center" prop="colNo"/>
      <el-table-column label="层数" align="center" prop="secNum"/>
      <el-table-column label="节数" align="center" prop="layNum"/>
      <el-table-column label="每格盒数" align="center" prop="boxNum"/>
      <el-table-column label="开柜方向" align="center" prop="openDirection">
        <template #default="scope">
          <dict-tag :options="open_direction" :value="scope.row.openDirection"/>
        </template>
      </el-table-column>
      <el-table-column label="是否固定列" align="center" prop="isFixedCol">
        <template #default="scope">
          <dict-tag :options="column_fixed" :value="scope.row.isFixedCol"/>
        </template>
      </el-table-column>
      <el-table-column label="是否允许开柜" align="center" prop="isOpen">
        <template #default="scope">
          <dict-tag :options="open_lock" :value="scope.row.isOpen"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="400">
        <template #default="scope">
          <el-button type="text" icon="Upload" @click="handleOpen(scope.row)"
                     v-hasPermi="['archive:ArchiveCabinet:edit']"
                     v-if="scope.row.isFixedCol!='01'&&scope.row.isOpen!='02'">开架
          </el-button>
          <el-button type="text" icon="Download" @click="handleClose(scope.row)"
                     v-hasPermi="['archive:ArchiveCabinet:edit']"
                     v-if="scope.row.isFixedCol!='01'&&scope.row.isOpen!='02'">合架
          </el-button>
          <el-button type="text" icon="VideoPause" @click="handleStop(scope.row)"
                     v-hasPermi="['archive:ArchiveCabinet:edit']">停止
          </el-button>
          <el-button type="text" icon="Hide" @click="handleSecure(scope.row)"
                     v-hasPermi="['archive:ArchiveCabinet:edit']">解禁
          </el-button>
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['archive:ArchiveCabinet:edit']">设置
          </el-button>

          <!-- <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['archive:ArchiveCabinet:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" /> -->

    <!-- 添加或修改柜对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="ArchiveCabinetRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="档案区编号" prop="archiveAreaNo">
          <el-input v-model="form.archiveAreaNo" placeholder="请输入档案区编号" style="width:280px" readonly
                    disabled="disabled"/>
        </el-form-item>
        <el-form-item label="列编号" prop="colNo">
          <el-input v-model="form.colNo" placeholder="请输入列编号(档案柜编号)" style="width:280px" readonly
                    disabled="disabled"/>
        </el-form-item>
        <el-form-item label="层数" prop="secNum">
          <el-input v-model="form.secNum" placeholder="请输入层数" type="number" style="width:280px" readonly
                    disabled="disabled"/>
        </el-form-item>
        <el-form-item label="节数" prop="layNum">
          <el-input v-model="form.layNum" placeholder="请输入节数" type="number" style="width:280px" readonly
                    disabled="disabled"/>
        </el-form-item>
        <el-form-item label="每格盒数" prop="boxNum">
          <el-input v-model="form.boxNum" placeholder="请输入每格盒数" type="number" style="width:280px" readonly
                    disabled="disabled"/>
        </el-form-item>

        <el-form-item label="是否固定列" prop="isFixedCol">
          <el-select v-model="form.isFixedCol" placeholder="请选择是否固定列" style="width:280px">
            <el-option v-for="dict in column_fixed" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开柜方向" prop="openDirection">
          <el-select v-model="form.openDirection" placeholder="请选择开柜方向" style="width:280px">
            <el-option v-for="dict in open_direction" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否允许开柜" prop="isOpen">
          <el-select v-model="form.isOpen" placeholder="请选择是否允许开柜" style="width:280px">
            <el-option v-for="dict in open_lock" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ArchiveCabinet">
import {
  listArchiveArchArea
} from "@/api/archive/ArchiveArchArea";
import {
  listArchiveCabinet,
  getArchiveCabinet,
  delArchiveCabinet,
  addArchiveCabinet,
  updateArchiveCabinet,
  //获取服务器ip
  getServerIp
} from "@/api/archive/ArchiveCabinet";
import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  onMounted,
  onUnmounted
} from "vue";

const {
  proxy
} = getCurrentInstance();

const ArchiveArchAreaList = ref([]);
const ArchiveCabinetList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const serverIp = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    orgNo: null,
    archivesRoomId: null,
    archiveAreaId: null,
    archiveAreaNo: null,
    colNo: null,
    secNum: null,
    layNum: null,
    boxNum: null,
    isFixedCol: null,
    openDirection: null,
    fixedColNo: null,
    parentColNo: null,
    type: null,
    isOpen: null,
    secRfidNo: null,
  },
  rules: {}
});

const {
  queryParams,
  form,
  rules
} = toRefs(data);
const {
  archive_type,
  open_direction,
  cabinet_type,
  open_lock,
  column_fixed
} = proxy.useDict('archive_type', 'open_direction', 'cabinet_type', 'open_lock', 'column_fixed');

/** 查询区列表 */
function getAreaList() {
  listArchiveArchArea(queryParams.value).then(response => {
    ArchiveArchAreaList.value = response.rows;
  });
}

/** 查询柜列表 */
function getList() {
  loading.value = true;
  queryParams.value.pageSize = 1000;
  listArchiveCabinet(queryParams.value).then(response => {
    loading.value = false;
    ArchiveCabinetList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orgNo: null,
    archivesRoomId: null,
    archiveAreaId: null,
    archiveAreaNo: null,
    colNo: null,
    secNum: null,
    layNum: null,
    boxNum: null,
    isFixedCol: null,
    openDirection: null,
    fixedColNo: null,
    parentColNo: null,
    type: null,
    isOpen: null,
    secRfidNo: null,
    createTime: null,
    creator: null,
    modifyTime: null,
    modifier: null
  };
  proxy.resetForm("ArchiveCabinetRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加档案柜";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getArchiveCabinet(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "设置档案柜";
    getList();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ArchiveCabinetRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateArchiveCabinet(form.value).then(response => {
          proxy.$modal.msgSuccess("设置成功");
          open.value = false;
          getList();
        });
      } else {
        addArchiveCabinet(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除柜编号为"' + id + '"的数据项？').then(function () {
    return delArchiveCabinet(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('archive/ArchiveCabinet/export', {
    ...queryParams.value
  }, `档案柜_${new Date().getTime()}.xlsx`)
}


//开架
function handleOpen(row) {
  let cabinetIp = getArchiveAreaIp(row.archiveAreaNo);
  if (cabinetIp) {
    reset();
    const id = row.id || ids.value

    // 获取固定列
    const targetItem = ArchiveCabinetList.value.find(item => item.isOpen === '02'&& row.archiveAreaNo ===item.archiveAreaNo );
    const colNo = targetItem?.colNo ?? null;
    const controlLeftCode = colNo == 1 ? 1 : colNo / 2;
    console.log("固定列：" + controlLeftCode);
    // sort  0 从左至右 1 从右至左

    var columnNo = 0;
    var sort = 0;
    columnNo = (parseInt(row.colNo) + 1) / 2;
    var faceNo = 0;

    if (row.openDirection == "right") {
      sort = 0
    } else {
      sort = 1
    }
    if ((parseInt(row.colNo) + 1) % 2 == 0) {
      faceNo = sort == 0 ? 1 : 2;
    } else {
      faceNo = sort == 0 ? 2 : 1;
    }

    var area = "";
    // 左区
    if ((sort == 0 && columnNo < controlLeftCode) || (sort == 1 && columnNo > controlLeftCode)) {
      area = "left";
      // 右区
    } else if ((sort == 0 && columnNo > controlLeftCode) || (sort == 1 && columnNo < controlLeftCode)) {
      area = "right";
    } else if (columnNo == controlLeftCode) {
      if (1 == faceNo) {
        area = "left";
      } else if (2 == faceNo) {
        area = "right";
      } else {
        area = "right";
      }
    }
    // 往右开  parseInt(row.colNo - 1) / 2 + (row.colNo % 2 == 0 ? 1 : 0)

    const data = {
      "code": "open",
      "ip": cabinetIp,
      "faceNo": faceNo,
      "warehouseCode": row.archiveAreaNo,
      "areaCode": row.archiveAreaNo,
      "area": area,
      "columnNo": columnNo
    };

    sendMessage(data);

  }
}

var areaClose = 'left';

//合架
function handleClose(row) {
  let cabinetIp = getArchiveAreaIp(row.archiveAreaNo);
  var columnNo = 0;
  var sort = 0;
  if (row.openDirection == 'right') {
    columnNo = parseInt(row.colNo - 1) / 2 + (row.colNo % 2 == 0 ? 1 : 0);
    sort = 0;
  } else {
    columnNo = Math.ceil((parseInt(row.colNo) + 1) / 2);
    sort = 1;
  }
  // 获取固定列
  const targetItem = ArchiveCabinetList.value.find(item => item.isOpen === '02'&& row.archiveAreaNo ===item.archiveAreaNo );
  const colNo = targetItem?.colNo ?? null;
  const controlLeftCode = colNo == 1 ? 1 : colNo / 2;
  console.log("固定列：" + controlLeftCode);
  var area = "";
  // 左区
  if ((sort == 0 && columnNo < controlLeftCode) || (sort == 1 && columnNo > controlLeftCode)) {
    area = "left";
    // 右区
  } else if ((sort == 0 && columnNo > controlLeftCode) || (sort == 1 && columnNo < controlLeftCode)) {
    area = "right";
  } else if (columnNo == controlLeftCode) {
    area = "right";
  }

  if (cabinetIp) {
    reset();
    const id = row.id || ids.value

    const data = {
      "code": "close",
      "ip": cabinetIp,
      "warehouseCode": row.archiveAreaNo,
      "areaCode": row.archiveAreaNo,
      "area": area,
    };
    sendMessage(data);
  }
}

//停止
function handleStop(row) {
  let cabinetIp = getArchiveAreaIp(row.archiveAreaNo);
  var columnNo = 0;
  var sort = 0;
  if (row.openDirection == 'right') {
    columnNo = parseInt(row.colNo - 1) / 2 + (row.colNo % 2 == 0 ? 1 : 0);
    sort = 0;
  } else {
    columnNo = Math.ceil((parseInt(row.colNo) + 1) / 2);
    sort = 1;
  }
  // 获取固定列
  const targetItem = ArchiveCabinetList.value.find(item => item.isOpen === '02'&& row.archiveAreaNo ===item.archiveAreaNo );
  const colNo = targetItem?.colNo ?? null;
  const controlLeftCode = colNo == 1 ? 1 : colNo / 2;
  console.log("固定列：" + controlLeftCode);
  var area = "";
  // 左区
  if ((sort == 0 && columnNo < controlLeftCode) || (sort == 1 && columnNo > controlLeftCode)) {
    area = "left";
    // 右区
  } else if ((sort == 0 && columnNo > controlLeftCode) || (sort == 1 && columnNo < controlLeftCode)) {
    area = "right";
  } else if (columnNo.equals(controlLeftCode)) {
    area = "right";
  }

  if (cabinetIp) {
    reset();
    const id = row.id || ids.value

    const data = {
      "code": "stop",
      "ip": cabinetIp,
      "warehouseCode": row.archiveAreaNo,
      "areaCode": row.archiveAreaNo,
      "area": area,
    };
    sendMessage(data);
  }
}

//解禁
function handleSecure(row) {

  let cabinetIp = getArchiveAreaIp(row.archiveAreaNo);
  var columnNo = 0;
  var sort = 0;
  if (row.openDirection == 'right') {
    columnNo = parseInt(row.colNo - 1) / 2 + (row.colNo % 2 == 0 ? 1 : 0);
    sort = 0;
  } else {
    columnNo = Math.ceil((parseInt(row.colNo) + 1) / 2);
    sort = 1;
  }
  // 获取固定列
  const targetItem = ArchiveCabinetList.value.find(item => item.isOpen === '02'&& row.archiveAreaNo ===item.archiveAreaNo );
  const colNo = targetItem?.colNo ?? null;
  const controlLeftCode = colNo == 1 ? 1 : colNo / 2;
  console.log("固定列：" + controlLeftCode);
  var area = "";
  // 左区
  if ((sort == 0 && columnNo < controlLeftCode) || (sort == 1 && columnNo > controlLeftCode)) {
    area = "left";
    // 右区
  } else if ((sort == 0 && columnNo > controlLeftCode) || (sort == 1 && columnNo < controlLeftCode)) {
    area = "right";
  } else if (columnNo == controlLeftCode) {
    area = "right";
  }
  if (cabinetIp) {
    reset();
    const id = row.id || ids.value

    const data = {
      "code": "unlock",
      "ip": cabinetIp,
      "warehouseCode": row.archiveAreaNo,
      "areaCode": row.archiveAreaNo,
      "area": area,
    };
    sendMessage(data);
  }
}

function getArchiveAreaIp(archiveAreaNo) {
  let cabinetIp;
  for (let item of ArchiveArchAreaList.value) {
    if (item.archAreaNo === archiveAreaNo) {
      cabinetIp = item.cabinetIp;
      break;
    }
  }
  return cabinetIp;
}

let socket = null;
const receivedMessage = ref('');


function useWebSocket(url) {
  socket = new WebSocket(url);
  socket.onopen = () => {
    console.log('WebSocket connection opened');
  };
  socket.onmessage = (event) => {
    receivedMessage.value = event.data;
  };

  socket.onerror = (error) => {
    console.error('WebSocket error:', error);
  };

  socket.onclose = () => {
    console.log('WebSocket connection closed');
  };
}

const disconnect = () => {
  if (socket) {
    socket.close();
  }
};

const sendMessage = (message) => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    console.log("这是返回值" + JSON.stringify(message));
    socket.send(JSON.stringify(message));
  } else {
    console.error('WebSocket is not open or not connected.');
  }
};

// 获取服务器 IP
function fetchServerIp() {
  getServerIp().then(response => {
    serverIp.value = response.msg;
    // 在获取到 serverIp 后调用 useWebSocket
    useWebSocket("ws://" + serverIp.value + ":9100/shelvesocket");
  }).catch(error => {
    console.error('Failed to fetch server IP:', error);
  });
}


getList();
getAreaList();
fetchServerIp();
</script>
